#include "StdAfx.h"
#include ".\webfiles.h"


extern  unsigned char g_webFileData[];
extern  DWORD g_dwWebFileDataSize;


string GetStaticHeader(void)
{
	return GetWebFileContent( L"/files/header.html" );
	//return string( (char*)g_dwWfHeaderData, g_dwWfHeaderSize );	
}

string GetStaticFooter(void)
{
	return GetWebFileContent( L"/files/footer.html" );
}

string  ScanWebFiles( wstring strRoot, LPCTSTR lpszFolder )
{
	string strContent;

	
	CFindFile cff;
	BOOL bFound = FALSE;
	WCHAR szSearch[MAX_PATH] = {0};

	int nCharCount = wsprintf( szSearch, L"%s\\*", lpszFolder );

	bFound = cff.FindFile( szSearch );
	while( bFound )
	{
		wstring strFileName = cff.GetFileName( );
		wstring strFilePath = cff.GetFilePath( );

		if( cff.IsDots( ) )
		{

		}
		else if( cff.IsDirectory() )
		{
			// folder
			wstring strNewRoot = strRoot;
			strNewRoot += L"/";
			strNewRoot += strFileName;
			strContent += ScanWebFiles( strNewRoot,  strFilePath.c_str() );
		}
		else 
		{
			// file
			DWORD dwFileSize = (DWORD)cff.GetFileSize(); 
			if( dwFileSize > 0 )
			{
				WCHAR padding = 0;
				WebFileInfo info = {0};

				info.dwFlags = TRUE;
				info.dwFileSize = dwFileSize;


				strContent += string( (char*)&info, sizeof(WebFileInfo) );	

				strContent += string( (char*)strRoot.c_str(), wcslen( strRoot.c_str() )*sizeof(WCHAR) );
				
				padding = '/';
				strContent += string( (char*)&padding, sizeof(WCHAR) );

				strContent += string( (char*)strFileName.c_str(), wcslen( strFileName.c_str() )*sizeof(WCHAR) );
				
				padding = '\0';
				strContent += string( (char*)&padding, sizeof(WCHAR) );

				strContent += UTIL_ReadFile( strFilePath.c_str() );
				
			}

		}	

		bFound = cff.FindNextFile( );
	}


	cff.Close( );   

	return strContent;
}

string GetWebFileContent( LPCTSTR lpszPath,  const BYTE* lpData, DWORD dwFileSize )
{
	string strData;
	DWORD dwStep = 0;
	size_t  iSrcLen = wcslen( lpszPath );

	while( dwStep < dwFileSize )
	{

		WebFileInfo info = {0};
		memcpy( &info,  lpData + dwStep,  sizeof(WebFileInfo) );

		if( info.dwFlags != TRUE )
			break;

		WCHAR* lpUrl = (WCHAR*)( lpData + dwStep + sizeof(WebFileInfo) );
		size_t len = wcslen( lpUrl );	

		if( ( len == iSrcLen ) &&
			(_wcsicmp( lpUrl, lpszPath ) == 0 ) &&
			( dwStep + sizeof(WebFileInfo) ) )
		{
			char* lpFileData = (char*)( lpData + dwStep + sizeof(WebFileInfo) + (len+1)*sizeof(WCHAR) );
			strData = string( lpFileData, info.dwFileSize  );
			break;
		}

		dwStep += sizeof(WebFileInfo) + (len+1)*sizeof(WCHAR) + info.dwFileSize; 

	}

	return strData;
}

string GetWebFileContent( LPCTSTR lpszPath )
{
	  return GetWebFileContent( lpszPath, g_webFileData, g_dwWebFileDataSize );
}
	
